import { _decorator, Button, CCInteger, Component, Label, Node, Sprite, tween, Tween, TweenAction, Animation } from 'cc';
import { SoundManager } from '../manager/SoundManger';
import { GameData } from '../system/GameData';
import { DataHelper } from '../system/DataHelper';
import { TurnTableItem } from './TurnTableItem';
import { AppControll, EventName, PopView, turntable_config } from '../manager/AppControll';
import { Tools } from '../tools/Tools';
import EvtManger from '../tools/EvtManger';
import { PopManager } from '../manager/PopManager';
import { SystemMessage } from './SystemMessage';
const { ccclass, property } = _decorator;

@ccclass('DailyTurntable')
export class DailyTurntable extends Component {
    @property(CCInteger)
    mSpeed = 360;

    private mNdTimes: Node = null;
    private mNdTable: Node = null;
    private mNBaseId: number = 140000
    private mNdBtnFree: Node = null;
    private mNdBtnAd: Node = null;
    private mLtConfig: turntable_config[] = [];
    private mBIsLock: boolean = false;



    private isRotating: boolean = false; // 是否正在旋转

    protected onLoad(): void {
        GameData.isPause = true;
        let body = this.node.getChildByName("body");
        this.mNdTable = body.getChildByName("turntable").getChildByName("reward");
        this.mNdTimes = body.getChildByName("turntable").getChildByName("times");
        this.mNdBtnFree = body.getChildByName("turntable").getChildByName("definBtn");
        this.mNdBtnAd = body.getChildByName("turntable").getChildByName("VideoBtn");
        this.InitReward();
        this.InitView();
    }

    InitView() {
        let freeTimes = GameData.GetTurnFreeTimes();
        let adTimes = GameData.GetTurnADTimes();
        this.mNdTimes.getComponent(Label).string = (freeTimes + adTimes).toString();
        if (GameData.playerData.turntableFreeTimes <= 0 && GameData.playerData.turntableVideoTimes > 0) {
            this.mNdBtnFree.active = false;
            this.mNdBtnAd.active = true;
        } else if (GameData.playerData.turntableFreeTimes <= 0 && GameData.playerData.turntableVideoTimes <= 0) {
            this.mNdBtnFree.active = false;
            this.mNdBtnAd.active = true;
            this.mNdBtnAd.getComponent(Button).interactable = false;
            this.mNdBtnAd.getComponent(Sprite).grayscale = true;
        } else if (GameData.playerData.turntableFreeTimes > 0) {
            this.mNdBtnFree.active = true;
            this.mNdBtnAd.active = false;
        }
    }

    start() {

    }

    InitReward() {
        let config = DataHelper.GetTurntableConfig();
        let arr = this.mNdTable.getChildByName("itemList").children;
        let index = 0;
        for (const key in config) {
            if (Object.prototype.hasOwnProperty.call(config, key)) {
                this.mLtConfig.push(config[key]);
                const element = config[key];
                if (arr[index]) {
                    arr[index].addComponent(TurnTableItem).InitItem(element);
                }
                index++;
            }
        }

    }

    startRotate(result: number) {
        if (this.isRotating) return;
        this.mNdTable.getChildByName("itemList").children.forEach(nd => {
            nd.getComponent(Animation).stop();
        })

        this.mNdTable.angle = 0;
        this.isRotating = true;

        // 计算旋转角度，奖励区域总数为12，每个区域30度
        let angle = result * 30;

        // 计算实际结束角度
        let endAngle = angle + 360 * (2 + Math.floor(Math.random() * 3)); // 假设转动5圈

        const dropAnimation = tween()
            .to(endAngle / this.mSpeed, { angle: endAngle }, { easing: 'fade' })
            .call(() => {
                this.mNdTable.getChildByName("itemList").children[result].getComponent(Animation).play();
                this.DoResult(this.mLtConfig[result]);
                this.isRotating = false;
            })
        tween(this.mNdTable)
            .then(dropAnimation)
            .start();
    }

    onClose() {
        GameData.isPause = false;
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        this.node.destroy();
    }

    OnBtnFree() {
        if (!this.mLtConfig) return;
        AppControll.Platform.SendBuryPoint(100019);
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        if (this.isRotating) return;
        if (GameData.playerData.turntableFreeTimes <= 0) return;
        this.startRotate(this.GetResult());
        GameData.playerData.turntableFreeTimes--;
        this.InitView();
    }

    OnBtnAd() {
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        if (this.isRotating) return;
        if (!this.mLtConfig) return;
        if (this.mBIsLock) return;
        this.mBIsLock = true;
        this.scheduleOnce(() => {
            this.mBIsLock = false;
        }, 0.2)
        if (GameData.playerData.turntableVideoTimes <= 0) {
            PopManager.Instance<PopManager>().ShowPop(PopView.systemMessage, nd => {
                nd.getComponent(SystemMessage).InitContent("今日次数已用完，请明日再来！")
            })
            return;
        }
        AppControll.Platform.ShowRewardVideoAd(this, (bool: boolean, str: string) => {
            this.mBIsLock = false;
            if (bool) {
                AppControll.Platform.SendBuryPoint(100018);
                this.startRotate(this.GetResult());
                GameData.playerData.turntableVideoTimes--;
            }
        })
        this.InitView();
    }

    GetResult() {
        let arr = [];
        let result = null;
        for (let i = 0; i < this.mLtConfig.length; i++) {
            const element = this.mLtConfig[i];
            let temp = [];
            temp.push(element.rewardPosition - 1);
            temp.push(element.rewardWeight)
            arr.push(temp)
        }
        result = Tools.GetResultByWeightLt(arr);
        return result;
    }

    DoResult(config: turntable_config) {
        let id = config.rewardProp;
        let porpConfig = DataHelper.GetPropConfigById(id);
        let ref = DataHelper.GetMonsterRefreshByAuto();
        if (!ref) return
        if (!porpConfig) return
        switch (porpConfig.propType) {
            case 1:
                GameData.AddGold(porpConfig.propNum * ref.LimitedTimeAwardGold);
                EvtManger.do(EventName.dropGiftGold, this.mNdTable.parent.position);
                break;
            case 3:
                GameData.playerData.blueStuff += porpConfig.propNum
                EvtManger.do(EventName.dropMaterial, porpConfig, this.mNdTable.parent.position);
                break;
            case 4:
                GameData.playerData.purpleStuff += porpConfig.propNum
                EvtManger.do(EventName.dropMaterial, porpConfig, this.mNdTable.parent.position);
                break;
            case 5:
                GameData.playerData.yellowStuff += porpConfig.propNum
                EvtManger.do(EventName.dropMaterial, porpConfig, this.mNdTable.parent.position);
                break;
            case 6:
                GameData.playerData.redStuff += porpConfig.propNum
                EvtManger.do(EventName.dropMaterial, porpConfig, this.mNdTable.parent.position);
                break;
            case 7:
                EvtManger.do(EventName.dropPearls, porpConfig.propNum, this.node.position.add(this.node.parent.position));
                break;
        }
    }
}


